package cn.lanqiao.bigDate.api.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.lanqiao.bigDate.service.data.DataUserService;
import cn.lanqiao.common.utils.TokenUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;
/**
 * @author Marisa
 * @description 前端登录拦截器
 * @date 2022/4/7
 */
//public class LoginFilter implements WebMvcConfigurer
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private DataUserService userService;

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler)
        throws IOException {
        String tokenName = "Authorization";
        // 尝试从header中取token
        String token = request.getHeader(tokenName);
        // 尝试从参数中取token
        if (StrUtil.isEmpty(token)) {
            token = request.getParameter(tokenName);
        }
        // 尝试从cooke
        if (StrUtil.isEmpty(token)) {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if (Objects.equals(cookie.getName(), tokenName)) {
                    token = cookie.getValue();
                }
            }
        }
        // 如果前端没有携带token返回json数据
        if (StrUtil.isBlank(token)) {
            PrintWriter pw = response.getWriter();
            pw.write(JSON.toJSONString("用户未登录"));
            return false;
        }
        //解析token
        boolean verify = TokenUtil.verify(token);
        if (verify) {
            return false;
        }
        // 获取用户ID
        String tokenUserId = TokenUtil.getUserName(token);
        // token存在，但是redis不存在。要么是失效，要么是强制下线
//        JwtInfo jwt = redis.get(RedisKey.getToken(tokenUserId, jwtId));
//        if (jwt == null || !jwt.getToken().equals(token)) {
//            throw new ServiceException(401, "您当前登录的账号已失效，请重新登录");
//        }
//        //获取用户ID
//        Long userId = jwt.getUserId();
//        //查询用户
//        User user = userService.selectById(userId);
//        //判断用户是否存在
//        if (user == null) {
//            throw new ServiceException(MsgCode.CODE_UNAUTHORIZED, "用户不存在");
//        }
//        //根据业务需求增加其他判断条件
//        if (user.getStatus() == 1) {
//            throw new ServiceException(MsgCode.CODE_UNAUTHORIZED, "用户已禁用！");
//        }
//        //将登录用户放到ThreadLocal变量变量中，方便业务获取当前登录用户
//        CurrentUser currentUser = new CurrentUser();
//        currentUser.setId(userId);
//        currentUser.setUserName(user.getAccountname());
//        currentUser.setNickName(user.getName());
//        //当前用户放到ThreadLocal变量变量中
//        CurrentUserUtil.set(currentUser);
        return true;
    }
}

